import os
from urllib.parse import quote_plus

from dotenv import load_dotenv
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

load_dotenv()

# 从环境变量中获取数据库配置
MYSQL_USERNAME = os.getenv("MYSQL_USERNAME", "fastapi")
MYSQL_PASSWORD = quote_plus(os.getenv("MYSQL_PASSWORD", "fastapi@123"))
MYSQL_URI = os.getenv("MYSQL_URI", "127.0.0.1:3306")
MYSQL_NAME = os.getenv("MYSQL_NAME", "fastapi-test")

# 构建数据库 URL
SQLALCHEMY_DATABASE_URL = f'mysql+aiomysql://{MYSQL_USERNAME}:{MYSQL_PASSWORD}@{MYSQL_URI}/{MYSQL_NAME}?charset=utf8'

# 创建异步数据库引擎
engine = create_async_engine(
    SQLALCHEMY_DATABASE_URL,
    pool_pre_ping=True,
    pool_recycle=3600,
    connect_args={"autocommit": False, "charset": "utf8mb4"}
)

# 创建异步会话工厂
async_session_factory = sessionmaker(
    bind=engine,
    class_=AsyncSession
)

# 创建基本的映射基类
Base = declarative_base()


async def init_db():
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)
